package com.pubinfo.passbook.api.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import com.pubinfo.passbook.api.service.TFeedbackFileService;
import com.pubinfo.passbook.common.entity.TFeedbackFile;
import com.pubinfo.passbook.common.mapper.TFeedbackFileMapper;
import com.pubinfo.passbook.common.model.dto.feedback.FeedbackParam;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xuhong
 * @since 2022-02-28
 */
@Service
public class TFeedbackFileServiceImpl extends ServiceImpl<TFeedbackFileMapper, TFeedbackFile> implements TFeedbackFileService {

    @Value("${post.url}")
    String postUrl;
    @Value("${post.http-port}")
    String httpPort;

    @Override
    public String addFeedbackFile(FeedbackParam feedbackVo) throws UnirestException {
        return postFeedbackFile(feedbackVo,postUrl + ":" + httpPort + "/api/FeedbackFile/saveFeedbackFile");
    }


    private String postFeedbackFile(FeedbackParam feedbackVo, String url) throws UnirestException {
        //Unirest.setTimeouts(0, 0);
        HttpResponse<String> response = Unirest.post(url)
                .header("User-Agent", "apifox/1.0.0 (https://www.apifox.cn)")
                .field("multipartFiles", transferToFile(feedbackVo.getMultipartFiles()))
                .field("feedbackId", feedbackVo.getTPersonFeedback().getId())
                .asString();
        return response.getBody();
    }

    private List<File> transferToFile(List<MultipartFile> multipartFiles) {
        List<File> list=new ArrayList<>();
//        选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        for (MultipartFile multipartFile : multipartFiles) {
            File file = null;
            try {
                String originalFilename = multipartFile.getOriginalFilename();
                int index= originalFilename.lastIndexOf(".");
                file = File.createTempFile(originalFilename.substring(0,index),originalFilename.substring(index));
                multipartFile.transferTo(file);
                list.add(file);
                file.deleteOnExit();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
}
